import com.fasterxml.jackson.databind.ObjectMapper;
import mode.Message;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 比特就业课
 * @Date 2023-04-02
 */
@WebServlet("/message")
public class MessageServlet extends HttpServlet {

    // 创建一个集合用来存储留言数据
    List<Message> messageList = new ArrayList<>();

    // 创建用于解析JSON的对象
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求与响应的编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        // 把list直接转成JSON字符串
        String jsonStr = objectMapper.writeValueAsString(messageList);
        // 直接写回应
        resp.getWriter().write(jsonStr);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求与响应的编码格式
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");

        // 获取请求中的数据并转换成JAVA对象
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        // 加入校验
        if (message == null || message.getContent() == null || message.getSender() == null || message.getReceiver() == null) {
            // 设置响应内容
            resp.getWriter().write("{\"code\": -1}");
            return;
        }
        // 把留言数据加入到集合中
        messageList.add(message);
        // 打印日志
        System.out.println("提交的数据：" + objectMapper.writeValueAsString(message));
        System.out.println("list中的数据：" + objectMapper.writeValueAsString(messageList));

        // 设置响应内容
        resp.getWriter().write("{\"code\": 200}");
    }
}
